package com.mcb_wxc.controller;

import com.mcb_wxc.util.AliyunOSSUtil;
import com.mcb_wxc.util.CodeUtil;
import com.mcb_wxc.util.ReturnJsonResultUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("image")
public class ImageController {
	@RequestMapping("uploadImage")
	@ResponseBody
	public String uploadImage(Map<String, Object> params, HttpServletRequest request) {
		ReturnJsonResultUtil result = new ReturnJsonResultUtil();
		System.out.println("______________");
		//创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        String files = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM/dd");
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            try {
            	while(iter.hasNext()){
	                //取得上传文件  
	                MultipartFile file = multiRequest.getFile(iter.next());
	                if(file != null){
	                	String path = "upload/images/" + sdf.format(new Date()) + "/" + file.getOriginalFilename();
						AliyunOSSUtil.putObject(path, file);
						if(files.equals("")) {
							files += path;
						} else {
							files += "," + path;
						}
	                }
            	}
            } catch(Exception e) {
            	e.printStackTrace();
            	result.setResultCode(CodeUtil.FAIL);
            	result.setContent("ERROR: " + e.getMessage());
            }
            result.setResultCode(CodeUtil.SUCCESS);
            result.setMainData(files);
        } else {
        	result.setResultCode(CodeUtil.FAIL);
        	result.setContent("没有文件需要上传");
        }
		return result.toString();
	}

}
